package goupiao;

public class TicketThread implements Runnable {

    private int count = 10;
    private int num = 0;
    private int index = 0;

    @Override
    public void run() {
        while (sale()) {
        }
    }

    //同步锁，用关键字上锁，同一时间，只能一个线程来调用
    public synchronized boolean sale() {
        if (count == 0) {
            System.out.println("抢票结束！");
            return false;
        }
        count--;
        num++;
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "抢到了第" + num + "张票，剩余" + count + "票");
        if (Thread.currentThread().getName().equals("黄牛党")) {
            return false;
        }
        return true;
    }
  /*  @Override  //同步代码块，只适合单个同步代码块。
    public void run() {
        synchronized (this) {
            while (true) {
                if (count == 0) {
                System.out.println("抢票结束！");
                break;
                 }
                count--;
                num++;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "抢到了第" + num + "张票，剩余" + count + "票");
            }
        }

    }*/
}
